﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ppt = Microsoft.Office.Interop.PowerPoint;

namespace ObjectModel.PowerPoint
{
    public class SlideEventsManager
    {
        readonly Dictionary<int, SlideEvents> mDict = new Dictionary<int, SlideEvents>();
        
        public SlideEventsManager(PresentationEvents events)
        {
            events.SlideDeleted += events_SlideDeleted;
            events.ShapeAdded += events_ShapeAdded;
            events.ShapeDeleted += events_ShapeDeleted;
            events.ShapeSelected += events_ShapeSelected;
            events.ShapeDeselected += events_ShapeDeselected;
            events.TextSelectionChanged += events_TextSelectionChangedWithinShape;
            events.ShapeSelectionChanged += events_WindowSelectionChanged;
        }

        public SlideEvents this[int key]
        {
            get
            {
                if (!mDict.ContainsKey(key))
                    mDict.Add(key, new SlideEvents());

                return mDict[key];
            }
        }

        void events_WindowSelectionChanged(Ppt.Selection Sel)
        {
            int slideID = Sel.SlideRange[1].SlideID;
            if (mDict.ContainsKey(slideID))
                this[slideID].OnSelectionChanged(Sel);
        }

        void events_SlideDeleted(object sender, SlideChangedEventArgs e)
        {
            int slideID = e.SlideInfo.Id;
            if (mDict.ContainsKey(slideID))
                mDict.Remove(slideID);
        }

        void events_ShapeAdded(object sender, ShapeChangedEventArgs e)
        {
            int slideID = e.ShapeInfo.SlideId;
            if (mDict.ContainsKey(slideID))
                this[slideID].OnShapeAdded(e);
        }

        void events_ShapeDeleted(object sender, ShapeChangedEventArgs e)
        {
            int slideID = e.ShapeInfo.SlideId;
            if (mDict.ContainsKey(slideID))
                this[slideID].OnShapeDeleted(e);
        }

        void events_ShapeSelected(object sender, ShapeChangedEventArgs e)
        {
            int slideID = e.ShapeInfo.SlideId;
            if (mDict.ContainsKey(slideID))
                this[slideID].OnShapeSelected(e);
        }

        void events_ShapeDeselected(object sender, ShapeChangedEventArgs e)
        {
            int slideID = e.ShapeInfo.SlideId;
            if (mDict.ContainsKey(slideID))
                this[slideID].OnShapeDeselected(e);
        }

        void events_TextSelectionChangedWithinShape(object sender, TextSelectionChangedWithinShapeEventArgs e)
        {
            Ppt.Slide slide = e.TextRange.GetParent<Ppt.Slide>();
            if (slide != null)
            {
                int slideID = slide.SlideID;
                if (mDict.ContainsKey(slideID))
                    this[slideID].OnTextSelectionChanged(e);
            }
        }
    }
}
